package com.essence.common.model;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
    @Override
    public void write(JsonWriter out, T value) throws IOException {
        if (value == null) {
            out.nullValue();
            return;
        }

        out.beginObject();
        out.name("name").value(value.name());

        // 获取枚举类的所有字段
        Field[] fields = value.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 跳过枚举的静态字段和name()方法
            if (field.isSynthetic() || Modifier.isStatic(field.getModifiers())) {
                continue;
            }

            try {
                field.setAccessible(true);
                Object fieldValue = field.get(value);
                out.name(field.getName()).value(fieldValue.toString());
            } catch (Exception e) {
                // 忽略无法访问的字段
            }
        }

        out.endObject();
    }

    @Override
    public T read(JsonReader in) throws IOException {
        if (in.peek() == null) {
            in.nextNull();
            return null;
        }

        String name = null;
        in.beginObject();
        while (in.hasNext()) {
            String fieldName = in.nextName();
            if ("name".equals(fieldName)) {
                name = in.nextString();
                break;
            }
            in.skipValue();
        }
        in.endObject();

        if (name != null) {
            try {
                @SuppressWarnings("unchecked")
                Class<T> enumClass = (Class<T>) Class.forName(in.getClass().getName());
                return Enum.valueOf(enumClass, name);
            } catch (Exception e) {
                return null;
            }
        }

        return null;
    }
}